package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.ApUserDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * app用户登录
     * @param apUserDto
     * @return
     */
    @Override
    public ResponseResult login(ApUserDto apUserDto) {
        //1，判断用户名，密码是否为空
        if(StringUtils.isNotBlank(apUserDto.getPhone()) && StringUtils.isNotBlank(apUserDto.getPassword())){
            //2，验证用户是否存在
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper();
            wrapper.eq(ApUser::getPhone,apUserDto.getPhone());
            ApUser apUser = getOne(wrapper);
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //3，验证密码是否正确
            String pswd = DigestUtils.md5DigestAsHex((apUserDto.getPassword()+apUser.getSalt()).getBytes());
            if (!pswd.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //4，返回数据
            HashMap map = new HashMap();
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
            return ResponseResult.okResult(map);
        }else{
            //5，游客登录
            HashMap map = new HashMap();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
